package com.example.project.service.impl;

import com.example.project.entity.GoodsBean;
import com.example.project.mapper.ExcelMapper;
import com.example.project.service.ExcelService;
import com.example.project.vo.readExcel.ReadExcel;
import com.example.project.vo.writExcel.WritExcel;
import com.example.project.vo.writExcel.WritExcelTemplate;
import com.example.utils.resultFormat.Result;
import com.example.utils.resultFormat.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

/**
 * @author admin
 */
@Service
@Transactional  //实现事务回滚,这里可以不用写.如果要用记得在入口处添加注解@EnableTransactionManagement //开启声明式事务
public class ExcelServiceImpl implements ExcelService {

    @Autowired
    ExcelMapper excelMapper;

    /**
     * 导出报表板模
     */
    @Override
    public void exportExcelTemplate(HttpServletRequest request, HttpServletResponse response) {
        String[] column = {"序号","商品名称", "商品价格", "商品产地", "商品详细","上架时间"};
        WritExcelTemplate.exportExcelTemplate(request,response,"商品信息","商品信息","商品信息表",column,5);
    }

    /**
     * 读取excel中的数据,生成list
     */
    @Override
    public Result readExcelFile(MultipartFile file) {
        String result = "";
        //创建处理EXCEL的类
        ReadExcel readExcel = new ReadExcel();
        //解析excel，获取上传的事件单
        List<Map<String, Object>> goodInfoExcel = readExcel.getExcelInfo(file);

        int successTotal =  excelMapper.insertGoodInfo(goodInfoExcel);

        if(successTotal < 0 ){
            return ResultUtil.error("上传失败");
        }
        return ResultUtil.success(successTotal);
    }

    /**
     * 导出报表
     */
    @Override
    public void exportExcel(HttpServletRequest request, HttpServletResponse response) {
        //获取数据
//        List<GoodsBean> goodsBeanList = excelMapper.selectAll();

        List<GoodsBean> goodsBeanList = excelMapper.selectExportInfo();
        String[] column = {"序号","商品名称", "商品价格", "商品产地", "商品详细","上架时间","创建时间"};
        WritExcel.exportExcel(request,response,"商品信息","商品信息","商品信息表",column,6, goodsBeanList);
    }

    /**
     * 导出报表
     */
    @Override
    public List<GoodsBean> getExcelInfo() {
        //获取数据
        List<GoodsBean> goodsBeanList = excelMapper.selectAll();
        return goodsBeanList;
    }

    @Override
    public boolean saveBatch(List<GoodsBean> list) {
       int batch = excelMapper.saveBatch(list);
       if (batch>0){
           return true;
       }else {
           return false;
       }
    }
}
